package com.xhs.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.xhs.model.QrCodeResult;
import com.xhs.model.SearchTask;
import com.xhs.model.User;
import com.xhs.manager.QrCodeResultManager;
import com.xhs.manager.SearchTaskManager;
import com.xhs.manager.UserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 任务管理服务
 *
 * @author xhs
 */
@Slf4j
@Service
public class TaskService {

    @Autowired
    private SearchTaskManager searchTaskManager;

    @Autowired
    private QrCodeResultManager qrCodeResultManager;

    @Autowired
    private UserManager userManager;

    /**
     * 创建搜索任务
     */
    public Long createTask(String phoneNumber, String taskName, List<String> keywords, Integer executeInterval, Integer postTimeLimit, Integer searchPages) {
        // 查找用户
        User user = userManager.findByPhoneNumber(phoneNumber);
        if (user == null) {
            log.error("用户不存在，无法创建任务: phoneNumber={}", phoneNumber);
            return null;
        }
        
        SearchTask task = new SearchTask();
        task.setUserId(user.getId());
        task.setPhoneNumber(phoneNumber);
        task.setTaskName(taskName);
        // 直接保存为逗号分隔的字符串，而不是JSON格式
        task.setKeywords(String.join("，", keywords));
        task.setStatus("PENDING");
        task.setExecuteInterval(executeInterval != null ? executeInterval : 10);
        task.setPostTimeLimit(postTimeLimit != null ? postTimeLimit : 4);
        task.setSearchPages(searchPages != null ? searchPages : 1);
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        task.setTotalQrCodes(0);

        // 保存任务到MySQL
        boolean success = searchTaskManager.save(task);
        if (success) {
            log.info("创建搜索任务成功: id={}, phoneNumber={}, taskName={}, executeInterval={}, postTimeLimit={}, searchPages={}", 
                    task.getId(), phoneNumber, taskName, executeInterval, postTimeLimit, searchPages);
            return task.getId();
        } else {
            log.error("创建搜索任务失败: phoneNumber={}, taskName={}", phoneNumber, taskName);
            return null;
        }
    }

    /**
     * 创建搜索任务（兼容老接口）
     */
    public Long createTask(String phoneNumber, String taskName, List<String> keywords, Integer executeInterval, Integer postTimeLimit) {
        return createTask(phoneNumber, taskName, keywords, executeInterval, postTimeLimit, 1);
    }

    /**
     * 创建搜索任务（最简单接口，兼容老接口）
     */
    public Long createTask(String phoneNumber, String taskName, List<String> keywords) {
        return createTask(phoneNumber, taskName, keywords, 10, 4, 1);
    }

    /**
     * 获取所有待执行的任务
     */
    public List<SearchTask> getPendingTasks() {
        List<SearchTask> tasks = searchTaskManager.findPendingTasks();
        log.info("获取待执行任务数量: {}", tasks.size());
        return tasks;
    }

    /**
     * 获取用户的所有任务
     */
    public List<SearchTask> getUserTasks(String phoneNumber) {
        User user = userManager.findByPhoneNumber(phoneNumber);
        if (user == null) {
            log.warn("用户不存在: phoneNumber={}", phoneNumber);
            return new ArrayList<>();
        }
        
        List<SearchTask> tasks = searchTaskManager.findByUserId(user.getId());
        log.info("获取用户任务列表: phoneNumber={}, taskCount={}", phoneNumber, tasks.size());
        return tasks;
    }

    /**
     * 获取任务详情
     */
    public SearchTask getTask(Long id) {
        SearchTask task = searchTaskManager.getById(id);
        if (task != null) {
            log.info("获取任务详情成功: id={}", id);
        } else {
            log.warn("任务不存在: id={}", id);
        }
        return task;
    }

    /**
     * 更新任务状态
     */
    public void updateTaskStatus(Long id, String status) {
        SearchTask task = searchTaskManager.getById(id);
        if (task != null) {
            task.setStatus(status);
            task.setUpdateTime(LocalDateTime.now());
            boolean success = searchTaskManager.updateById(task);
            if (success) {
                log.info("更新任务状态成功: id={}, status={}", id, status);
            } else {
                log.error("更新任务状态失败: id={}, status={}", id, status);
            }
        } else {
            log.warn("任务不存在，无法更新状态: id={}", id);
        }
    }



    /**
     * 保存扫描结果
     */
    public void saveQrCodeResult(Long id, QrCodeResult qrCodeResult) {
        SearchTask task = searchTaskManager.getById(id);
        if (task == null) {
            log.warn("任务不存在，无法保存扫描结果: id={}", id);
            return;
        }
        
        // 检查是否已存在相同的二维码
        if (qrCodeResultManager.existsByTaskIdAndQrCodeUrl(id, qrCodeResult.getQrCodeUrl())) {
            log.info("二维码已存在，跳过保存: taskId={}, qrCodeUrl={}", id, qrCodeResult.getQrCodeUrl());
            return;
        }
        
        // 设置任务相关信息
        qrCodeResult.setTaskId(id);
        qrCodeResult.setTaskName(task.getTaskName());
        qrCodeResult.setUserId(task.getUserId());
        qrCodeResult.setPhoneNumber(task.getPhoneNumber());
        qrCodeResult.setCreateTime(LocalDateTime.now());
        qrCodeResult.setUpdateTime(LocalDateTime.now());

        // 保存扫描结果到MySQL
        boolean success = qrCodeResultManager.save(qrCodeResult);
        if (success) {
            // 更新任务的二维码总数
            task.setTotalQrCodes(task.getTotalQrCodes() + 1);
            task.setUpdateTime(LocalDateTime.now());
            searchTaskManager.updateById(task);
            
            log.info("保存扫描结果成功: id={}, qrCodeUrl={}", id, qrCodeResult.getQrCodeUrl());
        } else {
            log.error("保存扫描结果失败: id={}", id);
        }
    }

    /**
     * 获取任务的扫描结果
     */
    public List<QrCodeResult> getTaskResults(Long id) {
        List<QrCodeResult> results = qrCodeResultManager.findByTaskId(id);
        log.info("获取任务扫描结果: id={}, resultCount={}", id, results.size());
        return results;
    }

    /**
     * 根据任务名称获取扫描结果
     */
    public List<QrCodeResult> getTaskResultsByName(String phoneNumber, String taskName) {
        User user = userManager.findByPhoneNumber(phoneNumber);
        if (user == null) {
            log.warn("用户不存在: phoneNumber={}", phoneNumber);
            return new ArrayList<>();
        }

        List<SearchTask> tasks = searchTaskManager.findByUserIdAndTaskName(user.getId(), taskName);
        if (tasks.isEmpty()) {
            log.warn("任务不存在: phoneNumber={}, taskName={}", phoneNumber, taskName);
            return new ArrayList<>();
        }

        List<QrCodeResult> allResults = new ArrayList<>();
        for (SearchTask task : tasks) {
            List<QrCodeResult> results = qrCodeResultManager.findByTaskId(task.getId());
            allResults.addAll(results);
        }

        log.info("根据任务名称获取扫描结果: phoneNumber={}, taskName={}, resultCount={}", 
                phoneNumber, taskName, allResults.size());
        return allResults;
    }

        public boolean updateTaskKeywords(Long taskId, String keywords) {
        searchTaskManager.updateTaskKeywords(taskId, keywords);
        return true;
    }

    /**
     * 更新任务
     */
    public boolean updateTask(Long taskId, String keywords, Integer executeInterval, Integer postTimeLimit, Integer searchPages) {
        searchTaskManager.updateTask(taskId, keywords, executeInterval, postTimeLimit, searchPages);
        return true;
    }

    /**
     * 更新任务（兼容老接口）
     */
    public boolean updateTask(Long taskId, String keywords, Integer executeInterval, Integer postTimeLimit) {
        searchTaskManager.updateTask(taskId, keywords, executeInterval, postTimeLimit);
        return true;
    }
}